package com.hanqi.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 * <p>
 * 类名
 * </p>
 * <p>
 * 获取中文拼音工具类
 *
 * @author Administrator
 * @version 1.0
 */
public class PinyinUtil {

    /**
     * 得到 全拼
     *
     * @param src
     * @return
     */
    public static String getPingYin(String src) {
        return getPingYin(src, false);
    }

    /**
     * 得到 全拼
     *
     * @param src
     * @param headCharFlag 为true是获取拼音首字母
     * @return
     */
    public static String getPingYin(String src, boolean headCharFlag) {
        if (StringUtils.isEmpty(src)) {
            return null;
        }
        char[] srcCharArray = src.toCharArray();
        String[] stringArray;

        HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
        hanyuPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        hanyuPinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

        StringBuilder builder = new StringBuilder();
        try {
            for (char c : srcCharArray) {
                // 判断是否为汉字字符
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    stringArray = PinyinHelper.toHanyuPinyinStringArray(c, hanyuPinyinOutputFormat);
                    String temp = stringArray[0];
                    if (headCharFlag) {
                        builder.append(temp.charAt(0));
                        continue;
                    }
                    builder.append(temp);
                } else {
                    builder.append(c);
                }
            }
            return builder.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * 将字符串转移为ASCII码
     *
     * @param cnStr
     * @return
     */
    public static String getCnASCII(String cnStr) {
        StringBuilder strBuf = new StringBuilder();
        byte[] bytes = cnStr.getBytes();
        for (byte b : bytes) {
            strBuf.append(Integer.toHexString(b & 0xff));
        }
        return strBuf.toString();
    }
}
